package com.ruoyi.myplayer.controller;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.myplayer.domain.PlayerSong;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.myplayer.domain.PlayerVideo;
import com.ruoyi.myplayer.service.IPlayerVideoService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 视频Controller
 * 
 * @author ruoyi
 * @date 2025-04-12
 */
@RestController
@RequestMapping("/myplayer/video")
public class PlayerVideoController extends BaseController
{
    @Autowired
    private IPlayerVideoService playerVideoService;


    /**
     * 查询视频列表
     */
     @GetMapping("/list")
    public TableDataInfo list(PlayerVideo playerVideo)
    {
      //  startPage();
        List<PlayerVideo> list = playerVideoService.selectPlayerVideoList(playerVideo);
        return getDataTable(list);
    }

    /** 
    * @Description: 视频守护
     * @param id
    * @return: {@link java.lang.String}
    * @Author: lvyq
    * @Date: 2025/4/30 9:49
    */
    
    @GetMapping("/reUpdVideo")
    public String  reUpdSong(@RequestParam("id") Long id){
        PlayerVideo video = reUpdVideo(id);
        return video.getUrl();
    }

    private PlayerVideo reUpdVideo(Long id) {
        PlayerVideo video = playerVideoService.selectPlayerVideoById(id);

        if (video!=null) {
            Date nowDate = new Date();
            Date createTime = video.getCreateTime();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            long time = nowDate.getTime() - createTime.getTime();
            long m = time / 1000 / 60;
            if (m < 30) {
                return video;
            }

            if (video.getReNum() < 0) {
                return video;
            }

            String videoUrl = video.getReGuradUrl();
            String videoRes = HttpUtils.sendGet(videoUrl);
            Document videoDoc = Jsoup.parse(videoRes);

            //获取视频地址
            // 找到目标 <script> 标签
            Elements scriptTags = videoDoc.select("script");
            for (int i = 0; i < scriptTags.size(); i++) {

                String scriptContent = scriptTags.get(i).html();
                if (scriptContent.length() > 0 && scriptContent.contains("DPlayer")) {
                    // 提取 quality 数据
                    Pattern qualityPattern = Pattern.compile("quality:\\s*\\[(.*?)\\]", Pattern.DOTALL);
                    Matcher qualityMatcher = qualityPattern.matcher(scriptContent);

                    if (qualityMatcher.find()) {
                        String qualityBlock = qualityMatcher.group(1);
                        System.out.println("Quality Block: " + qualityBlock);

                        // 进一步解析每个 quality 项（可选，简单提取 name 和 url）
                        Pattern qualityItemPattern = Pattern.compile("\\{.*?name:\\s*'(.*?)'.*?url:\\s*'(.*?)'.*?\\}");
                        Matcher qualityItemMatcher = qualityItemPattern.matcher(qualityBlock);
                        while (qualityItemMatcher.find()) {
                            String name = qualityItemMatcher.group(1);
                            String vurl = qualityItemMatcher.group(2);
                            if (name.equals(video.getAutoName())) {
                                video.setUrl(vurl);
                                video.setCreateTime(new Date());
                                video.setReNum(video.getReNum() + 1);
                                video.setReUpdate(0l);
                                playerVideoService.updatePlayerVideo(video);
                            }

                        }
                    }
                    break;
                }
            }

        }       return video;
    }


    @GetMapping("/getHotMvLst")
    public TableDataInfo getHotMvLst(PlayerVideo playerVideo)
    {
        startPage();
        List<PlayerVideo> list = playerVideoService.getHotMvLst(playerVideo);
        return getDataTable(list);
    }


    /**
     * 导出视频列表
     */
    @PreAuthorize("@ss.hasPermi('myplayer:video:export')")
    @Log(title = "视频", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PlayerVideo playerVideo)
    {
        List<PlayerVideo> list = playerVideoService.selectPlayerVideoList(playerVideo);
        ExcelUtil<PlayerVideo> util = new ExcelUtil<PlayerVideo>(PlayerVideo.class);
        util.exportExcel(response, list, "视频数据");
    }

    /**
     * 获取视频详细信息
     */
    @PreAuthorize("@ss.hasPermi('myplayer:video:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(playerVideoService.selectPlayerVideoById(id));
    }

    /**
     * 新增视频
     */
    @PreAuthorize("@ss.hasPermi('myplayer:video:add')")
    @Log(title = "视频", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PlayerVideo playerVideo)
    {
        return toAjax(playerVideoService.insertPlayerVideo(playerVideo));
    }

    /**
     * 修改视频
     */
    @PreAuthorize("@ss.hasPermi('myplayer:video:edit')")
    @Log(title = "视频", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PlayerVideo playerVideo)
    {
        return toAjax(playerVideoService.updatePlayerVideo(playerVideo));
    }

    /**
     * 删除视频
     */
    @PreAuthorize("@ss.hasPermi('myplayer:video:remove')")
    @Log(title = "视频", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(playerVideoService.deletePlayerVideoByIds(ids));
    }


    public static void main(String[] args) throws ParseException {
        Map<String,Object> map = new HashMap<>();
        map.put("id","dm5rd25rZmZ5ag");
        map.put("type","music");
        HttpUtils.sendPost("http://www.w04.cn/static/js/play.php",
                JSONUtil.toJsonStr(map));
       // HttpUtil.post("http://www.78497.com/style/js/play.php?id=8e60f0a6a23f29caee77bd9ecdefe0bd&type=dance",map)
       // System.out.println("s = " + s);
    }
}
